package com.zkingsoft.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

public class HttpCurlUtil {
	
	
	/**
     * 向指定URL发送POST方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param data 请求参数，请求参数应该是json格式。
     */
	public static String sendPostHttp(String url,String data) throws HttpException, IOException {
		
        HttpClient httpClient = new HttpClient();  
        PostMethod post = new PostMethod(url);  
        post.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");  
        post.setRequestHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36");    
        post.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");  
        post.setRequestHeader("Connection","keep-alive");  
        RequestEntity entity = new StringRequestEntity(data, "text/html", "utf-8");  
        post.setRequestEntity(entity);  
        httpClient.executeMethod(post);  
      
        return post.getResponseBodyAsString();
	}
	
	/**
     * 向指定URL发送get方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param data 请求参数，请求参数应该是json格式。
     */
	public static String sendGetHttp(String url,Map<String, String> params) throws HttpException, IOException {
		  if (params != null) {
		      StringBuffer param = new StringBuffer();
		      int i = 0;
		      for (String key : params.keySet()) {
		        if (i == 0)
		          param.append("?");
		        else
		          param.append("&");
		        param.append(key).append("=").append((String)params.get(key));
		        i++;
		      }
		      url = url + param;
		    }
        HttpClient httpClient = new HttpClient();  
        GetMethod method = new GetMethod(url);   
        method.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");  
        method.setRequestHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36");  
        method.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");  
        method.setRequestHeader("Connection","keep-alive");  
        httpClient.executeMethod(method);  
        return method.getResponseBodyAsString();
	}
	
	
}
